package cn.swh.guguanjia.controller;

import cn.swh.guguanjia.util.FTPUtil;
import com.baidu.ueditor.ActionEnter;
import org.apache.commons.net.ftp.FTPClient;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: swh
 * @Description:
 * @Date: 2020/10/29 17:27
 * @Version: 1.0
 */
@RestController
public class UeditorController {

    @Value("${uploadPath}")
    String uploadPath;

    @Value("${staticPath}")
    String staticPath;

    @Value("${ftpHost}")
    String ftpHost;

    @Value("${ftpPort}")
    Integer ftpPort;

    @Value("${ftpUsername}")
    String ftpUsername;


    @Value("${ftpPassword}")
    String ftpPassword;


    @Value("${ftpUploadPath}")
    String ftpUploadPath;

    @Autowired
    FTPUtil ftpUtil;

    @RequestMapping("doUeditor")
    public String doUeditor(String action, HttpServletRequest request, MultipartFile upfile){
        String exec=null;
        if("config".equals(action)){
            exec = new ActionEnter( request, request.getServletContext().getRealPath("/") ).exec();
//            System.out.println(123);
        }else if("uploadimage".equals(action)){
            System.out.println(upfile);

            String filename = upfile.getOriginalFilename();
            String type = filename.substring(filename.lastIndexOf("."));
            File file = new File(uploadPath, filename);

            try {
                upfile.transferTo(file);
                FTPClient ftp = ftpUtil.getFTPClient(ftpHost, ftpPort, ftpUsername,ftpPassword);
                ftpUtil.uploadFile(ftp, file.getAbsolutePath(), ftpUploadPath);
                ftpUtil.closeFTP(ftp);
                exec = new JSONObject(resultMap("SUCCESS",filename,upfile.getSize(),filename,type,staticPath+filename)).toString();
            } catch (IOException e) {
                e.printStackTrace();
                exec = new JSONObject(resultMap("FAIL",null,0,null,null,null)).toString();
            }

        }
        return exec;
    }

    private Map<String,Object> resultMap(String state, String original, long size, String title, String type, String url){
        Map<String ,Object> result = new HashMap<>();
        result.put("state",state);
        result.put("original",original);
        result.put("size",size);
        result.put("title",title);
        result.put("type",type);
        result.put("url", url);
        return result;
    }

}
